package com.cyx.netty.n6;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.Scanner;

/*
closeFuture优雅关闭
客户端进程优雅结束

使用EventLoopServer1服务端
 */
@Slf4j
public class CloseFutureClient {
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup group = new NioEventLoopGroup();

        ChannelFuture channelFuture = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new StringEncoder());
                    }
                })
                .connect(new InetSocketAddress("localhost", 8888));
        Channel channel = channelFuture.sync().channel();
        log.info("连接建立成功...");
        new Thread(() -> {
            Scanner scanner = new Scanner(System.in);
            while (true) {
                String line = scanner.next();
                if ("q".equals(line)) {
                    // 异步非阻塞
                    channel.close();
                    break;
                }
                log.info("输出 {}", line);
                channel.writeAndFlush(line);
            }
        }, "input").start();

        // closeFuture处理关闭
        // 方法1.当channel没有断开时，线程阻塞，直到断开为止
//        ChannelFuture cf = channel.closeFuture().sync();
//        log.info("处理关闭之后的操作...");
//        group.shutdownGracefully();

        // 方法2. addListener处理关闭
        channel.closeFuture().addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                log.info("处理关闭之后的操作...");
                group.shutdownGracefully();
            }
        });
    }
}
